<?php
// 引入头部
require_once 'includes/header.php';

// 检查权限
if (!$current_user) {
    header('Location: /POS/login.php');
    exit;
}

// 处理操作
$action = $_GET['action'] ?? '';
$order_id = $_GET['id'] ?? 0;

// 处理已取餐操作
if ($action === 'mark_taken' && $order_id) {
    $sql = "UPDATE orders SET status = 'taken' WHERE id = ? AND status = 'completed'";
    Database::query($sql, [$order_id]);
    
    // 添加提示消息
    $_SESSION['alert'] = [
        'type' => 'success',
        'message' => '订单已标记为已取餐'
    ];
    
    // 获取更新后的订单信息，用于WebSocket通知
    $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
    
    // 发送WebSocket通知
    if ($order) {
        try {
            // 检查WebSocket客户端类是否存在
            if (file_exists(__DIR__ . '/../App/WebSocketClient.php')) {
                require_once __DIR__ . '/../App/WebSocketClient.php';
                $client = new \App\WebSocketClient();
                $result = $client->sendOrderStatusUpdate($order);
                
                if (!$result) {
                    error_log('发送WebSocket订单状态更新消息失败 (已取餐)');
                } else {
                    error_log('成功发送订单已取餐WebSocket消息，实时更新排队显示屏');
                }
            } else {
                error_log('WebSocketClient类不存在，无法发送WebSocket通知');
            }
        } catch (\Exception $e) {
            error_log('WebSocket通信错误: ' . $e->getMessage());
        }
    }
    
    // 重定向到订单列表
    header('Location: /POS/orders.php');
    exit;
}

// 处理订单状态更新
if ($action === 'update_status' && $order_id) {
    $status = $_POST['status'] ?? '';
    if ($status) {
        $sql = "UPDATE orders SET status = ? WHERE id = ?";
        Database::query($sql, [$status, $order_id]);
        
        // 添加提示消息
        $_SESSION['alert'] = [
            'type' => 'success',
            'message' => '订单状态已更新'
        ];
        
        // 获取更新后的订单信息，用于WebSocket通知
        $order = Database::fetch("SELECT * FROM orders WHERE id = ?", [$order_id]);
        
        // 发送WebSocket通知
        if ($order) {
            try {
                // 检查WebSocket客户端类是否存在
                if (file_exists(__DIR__ . '/../App/WebSocketClient.php')) {
                    require_once __DIR__ . '/../App/WebSocketClient.php';
                    $client = new \App\WebSocketClient();
                    $result = $client->sendOrderStatusUpdate($order);
                    
                    if (!$result) {
                        error_log('发送WebSocket订单状态更新消息失败 (status=' . $status . ')');
                    } else {
                        error_log('成功发送订单状态更新WebSocket消息 (status=' . $status . ')，实时更新排队显示屏');
                    }
                } else {
                    error_log('WebSocketClient类不存在，无法发送WebSocket通知');
                }
            } catch (\Exception $e) {
                error_log('WebSocket通信错误: ' . $e->getMessage());
            }
        }
        
        // 重定向到订单列表
        header('Location: /POS/orders.php');
        exit;
    }
}

// 处理订单删除
if ($action === 'delete' && $order_id && $current_user['role'] === 'admin') {
    // 先删除订单详情
    $sql = "DELETE FROM order_items WHERE order_id = ?";
    Database::query($sql, [$order_id]);
    
    // 再删除订单主表
    $sql = "DELETE FROM orders WHERE id = ?";
    Database::query($sql, [$order_id]);
    
    // 添加提示消息
    $_SESSION['alert'] = [
        'type' => 'success',
        'message' => '订单已删除'
    ];
    
    // 重定向到订单列表
    header('Location: /POS/orders.php');
    exit;
}

// 获取订单列表
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// 默认不显示已取餐的订单
$exclude_taken = true;
if (isset($_GET['show_taken'])) {
    $exclude_taken = false;
}

// 构建查询条件
$where = [];
$params = [];

if ($exclude_taken) {
    $where[] = "orders.status != 'taken'";
}

if ($search) {
    $where[] = "(orders.id LIKE ? OR users.name LIKE ? OR users.phone LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $where[] = "orders.status = ?";
    $params[] = $status_filter;
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// 查询订单总数
$count_sql = "SELECT COUNT(*) FROM orders 
              LEFT JOIN users ON orders.user_id = users.id 
              $where_clause";
$total = Database::fetchColumn($count_sql, $params);
$total_pages = ceil($total / $per_page);

// 查询订单列表
$sql = "SELECT orders.*, users.name as member_name, users.phone 
        FROM orders 
        LEFT JOIN users ON orders.user_id = users.id 
        $where_clause 
        ORDER BY orders.created_at DESC 
        LIMIT $offset, $per_page";
$orders = Database::fetchAll($sql, $params);
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-6">
            <h1 class="h3 mb-0">订单管理</h1>
            <p class="text-muted">查看和管理所有订单</p>
        </div>
        <div class="col-md-6 text-md-right">
            <a href="/POS/products.php" class="btn btn-primary">
                <i class="fas fa-plus-circle"></i> 新建订单
            </a>
        </div>
    </div>
    
    <!-- 过滤和搜索 -->
    <div class="card mb-4">
        <div class="card-body">
            <form action="" method="GET" class="row">
                <div class="col-md-4 mb-3 mb-md-0">
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                        </div>
                        <input type="text" class="form-control" name="search" placeholder="订单号/会员姓名/电话" value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                <div class="col-md-3 mb-3 mb-md-0">
                    <select name="status" class="form-control">
                        <option value="">全部状态</option>
                        <option value="paid" <?php echo $status_filter === 'paid' ? 'selected' : ''; ?>>待处理</option>
                        <option value="cooking" <?php echo $status_filter === 'cooking' ? 'selected' : ''; ?>>制作中</option>
                        <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>已完成</option>
                        <option value="cancelled" <?php echo $status_filter === 'cancelled' ? 'selected' : ''; ?>>已取消</option>
                        <option value="taken" <?php echo $status_filter === 'taken' ? 'selected' : ''; ?>>已取餐</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary btn-block">筛选</button>
                </div>
                <div class="col-md-2">
                    <a href="/POS/orders.php" class="btn btn-secondary btn-block">重置</a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 订单列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>订单号</th>
                            <th>会员信息</th>
                            <th>金额</th>
                            <th>支付方式</th>
                            <th>订单状态</th>
                            <th>下单时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($orders)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-4">没有找到相关订单</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($orders as $order): ?>
                        <tr>
                            <td>#<?php echo $order['id']; ?></td>
                            <td>
                                <?php if ($order['user_id']): ?>
                                <?php echo htmlspecialchars($order['member_name']); ?><br>
                                <small class="text-muted"><?php echo htmlspecialchars($order['phone']); ?></small>
                                <?php else: ?>
                                <span class="text-muted">非会员订单</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo number_format($order['total_amount'], 2); ?> 元</td>
                            <td>
                                <?php
                                $payment_method = '';
                                switch ($order['payment_method']) {
                                    case 'cash': $payment_method = '现金'; break;
                                    case 'member': $payment_method = '会员余额'; break;
                                    case 'card': $payment_method = '银行卡'; break;
                                    case 'wechat': $payment_method = '微信'; break;
                                    case 'alipay': $payment_method = '支付宝'; break;
                                    default: $payment_method = $order['payment_method']; break;
                                }
                                echo $payment_method;
                                ?>
                            </td>
                            <td>
                                <?php
                                $status_class = '';
                                $status_text = '';
                                switch ($order['status']) {
                                    case 'paid':
                                        $status_class = 'badge-warning';
                                        $status_text = '待处理';
                                        break;
                                    case 'cooking':
                                        $status_class = 'badge-info';
                                        $status_text = '制作中';
                                        break;
                                    case 'completed':
                                        $status_class = 'badge-success';
                                        $status_text = '已完成';
                                        break;
                                    case 'cancelled':
                                        $status_class = 'badge-danger';
                                        $status_text = '已取消';
                                        break;
                                    case 'taken':
                                        $status_class = 'badge-dark';
                                        $status_text = '已取餐';
                                        break;
                                    default:
                                        $status_class = 'badge-secondary';
                                        $status_text = $order['status'];
                                        break;
                                }
                                ?>
                                <span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                            </td>
                            <td><?php echo date('Y-m-d H:i', strtotime($order['created_at'])); ?></td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="/POS/order_detail.php?id=<?php echo $order['id']; ?>" class="btn btn-info">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <?php if ($order['status'] === 'completed'): ?>
                                    <a href="?action=mark_taken&id=<?php echo $order['id']; ?>" class="btn btn-success" onclick="return confirm('确定标记此订单为已取餐吗？');">
                                        <i class="fas fa-check-double"></i> 已取餐
                                    </a>
                                    <?php endif; ?>
                                    <?php if ($current_user['role'] === 'admin'): ?>
                                    <a href="#" onclick="confirmDelete(<?php echo $order['id']; ?>); return false;" class="btn btn-danger">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- 状态修改模态框 -->
                                <div class="modal fade" id="statusModal<?php echo $order['id']; ?>" tabindex="-1" role="dialog" aria-hidden="true">
                                    <div class="modal-dialog" role="document">
                                        <div class="modal-content">
                                            <form action="/POS/orders.php?action=update_status&id=<?php echo $order['id']; ?>" method="POST">
                                                <div class="modal-header">
                                                    <h5 class="modal-title">更新订单 #<?php echo $order['id']; ?> 状态</h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                        <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="form-group">
                                                        <label>订单状态</label>
                                                        <select name="status" class="form-control">
                                                            <option value="paid" <?php echo $order['status'] === 'paid' ? 'selected' : ''; ?>>待处理</option>
                                                            <option value="cooking" <?php echo $order['status'] === 'cooking' ? 'selected' : ''; ?>>制作中</option>
                                                            <option value="completed" <?php echo $order['status'] === 'completed' ? 'selected' : ''; ?>>已完成</option>
                                                            <option value="cancelled" <?php echo $order['status'] === 'cancelled' ? 'selected' : ''; ?>>已取消</option>
                                                            <option value="taken" <?php echo $order['status'] === 'taken' ? 'selected' : ''; ?>>已取餐</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                                                    <button type="submit" class="btn btn-primary">保存更改</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-4">
                <ul class="pagination justify-content-center">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// 删除确认
function confirmDelete(orderId) {
    if (confirm('确定要删除此订单吗？此操作不可恢复！')) {
        window.location.href = '/POS/orders.php?action=delete&id=' + orderId;
    }
}

// 显示提示消息
document.addEventListener('DOMContentLoaded', function() {
    <?php if (isset($_SESSION['alert'])): ?>
    showAlert('<?php echo $_SESSION['alert']['message']; ?>', '<?php echo $_SESSION['alert']['type']; ?>');
    <?php unset($_SESSION['alert']); ?>
    <?php endif; ?>
});
</script>

<?php
// 引入页脚
require_once 'includes/footer.php';
?> 